// 框架辅助类
var helper = require("../utils/common");
var express = require("express");
var router = express.Router();
// 模拟数据
var Mock = require("mockjs");
var Random = Mock.Random;
// 验证框架
var expressValidator = require('express-validator');

module.exports = function(app) {
    app.use(expressValidator());

    // 路由内部全局拦截器
    router.use(function(req, res, next) {
        helper.parseParams(req);
        next();
    });

    /**
     * 定义路由内数据类型
     */
    Random.extend({
        // 生成中文名
        chineseName: function(count) {
            var surnames = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦章云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐".split("");
            var forenames = "贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓".split("");
            if (typeof count !== "number") {
                count = Math.random() > .66
                    ? 2
                    : 3;
            }
            var surname = this.pick(surnames);
            var forename = "";
            count = count - 1;
            for (var i = 0; i < count; i++) {
                forename += this.pick(forenames);
            }
            return surname + forename;
        },
        // 用户信息
        mock_userinfo: function(id) {
            return Mock.mock({
                'id': id,
                'name': '@chineseName',
                'firstname': Random.string(4),
                'sex': (Random.boolean()
                    ? 1
                    : 0)
            });
        },
        // 用户列表
        mock_userlist: function(pagesize, offset) {
            return Mock.mock({
                'success': true,
                'data|1-10': ['@mock_userinfo(' + Random.natural() + ')'],
                'pagesize': pagesize,
                'offset': offset
            });
        },
        // 确认订单
        confirm_bill: function() {
            var success = Random.boolean();
            var template = {};
            if (success) {
                template = {
                    "Ret": success
                };
            } else {
                template = {
                    "Ret": success,
                    "Code": Random.natural(),
                    "Msg": "确认失败，请重试"
                };
            }
            return Mock.mock(template);
        },
        // 汽车监控-单个汽车
        vehicle_monitoring: function() {
            return Mock.mock({
                "VehicleID": ""+Random.natural()+"",
                "Brand": "丰田",
                "ImageUrl": "http://m.tiebaimg.com/timg?wapp&quality=80&size=b150_150&subsize=20480&cut_x=0&cut_w=0&cut_y=0&cut_h=0&sec=1369815402&srctrace&di=35a89cd4b869e742d3db80a60bcf1909&wh_rate=null&src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fpic%2Fitem%2Feac4b74543a982268ec5a8978282b9014a90eb7e.jpg",
                "PlateNumber": "川A" + Random.natural(1000,9999),
                "DriverID": ""+Random.natural()+"",
                "DriverName": "@chineseName",
                "Pos": {
                    "Lat": Random.float(34.777031, 34.817031, 6, 6),
                    "Long": Random.float(113.658807, 113.698807, 6, 6)
                },
                "Speed": Random.float( 20, 100, 1, 2),
                "IsOverSpeed": Random.boolean(),
                "Status": Random.natural(-3, 1)
            });
        },
        vehicle_monitoring_list: function(){
            var success = Random.boolean(1, 19, false);
            var template = {};
            if(success) {
                template = {
                    "Ret": success,
                    "Items|1-10": ['@vehicle_monitoring']
                };
            } else {
                template = {
                    "Ret": success,
                    "Code": Random.natural(),
                    "Msg": "获取车辆数据失败，请重试"
                };
            }

            return Mock.mock(template);
        },
        vehicle_search_list: function(pageSize, pageNum) {
            var success = Random.boolean(1, 19, false);
            var template = {};
            if(success) {
                template = {
                    "Ret": success,
                    "Items|0-15": ['@vehicle_monitoring']
                };
            } else {
                template = {
                    "Ret": success,
                    "Code": Random.natural(),
                    "Msg": "获取车辆数据失败，请重试"
                };
            }

            return Mock.mock(template);
        }
    });

    // 路由实现
    router.all('/login', function(req, res) {
        helper.initValidator(req);
        req.check('account', 'account is required.').notEmpty();
        req.check('verify', 'verify-code is required and must be integer.').notEmpty().isInt();

        var errors = req.validationErrors();
        if (helper.checkValidationError(errors)) {
            var params = req.params;
            var account = params.account;
            var pass = params.pass;

            res.status(200).json({
                "success": true,
                "msg": "登录成功，帐号:" + account + ", 密码:" + pass
            });
        } else {
            res.status(200).json({"success": false, "msg": "参数验证失败，请查看控制台信息"});
        }
    });

    router.all('/user/info/:id', function(req, res) {
        helper.initValidator(req);
        req.check('id', 'id is required and must be integer.').notEmpty().isInt();

        var errors = req.validationErrors();
        if (helper.checkValidationError(errors)) {
            var id = req.params.id;
            var userInfo = Mock.mock('@mock_userinfo(' + id + ')');

            res.status(200).json({success: true, user: userInfo});
        } else {
            res.status(200).json({"success": false, "result": "参数验证失败，请查看控制台信息"});
        }
    });

    router.all('/user/list', function(req, res) {
        helper.initValidator(req);
        console.log(req.params.offset);
        console.log(req.query.offset);
        req.check('pagesize', 'pagesize is required and must be integer.').notEmpty().isInt();
        req.check('offset', 'offset is required and must be integer.').notEmpty().isInt({allow_leading_zeroes: true});

        var errors = req.validationErrors();
        if (helper.checkValidationError(errors)) {
            var pagesize = req.params.pagesize;
            var offset = req.params.offset;
            var userList = Mock.mock('@mock_userlist(' + pagesize + ', ' + offset + ')');

            res.status(200).json(userList);
        } else {
            res.status(200).json({"success": false, "result": "参数验证失败，请查看控制台信息"});
        }
    });

    router.all('/bill/confirm', function(req, res) {
        helper.initValidator(req);
        req.check('OrderID', 'OrderID is required.').notEmpty();

        var errors = req.validationErrors();
        if (helper.checkValidationError(errors)) {
            var result = Mock.mock('@confirm_bill()');
            res.status(200).json(result);
        } else {
            res.status(200).json({"success": false, "result": "参数验证失败，请查看控制台信息"});
        }
    });

    router.all('/vehicle/monitoring/list', function(req, res) {
        helper.initValidator(req);

        var errors = req.validationErrors();
        if (helper.checkValidationError(errors)) {
            var result = Mock.mock('@vehicle_monitoring_list()');
            res.status(200).json(result);
        } else {
            res.status(200).json({"success": false, "result": "参数验证失败，请查看控制台信息"});
        }
    });

    router.all('/vehicle/search/list', function(req, res) {
        helper.initValidator(req);
        req.check('PageNum', 'OrderID is required and must be integer.').notEmpty().isInt();
        req.check('PageSize', 'OrderID is required and must be integer.').notEmpty().isInt();
        var errors = req.validationErrors();
        if (helper.checkValidationError(errors)) {
            var pageSize = req.params.PageSize;
            var pageNum = req.params.PageNum;

            var result = Mock.mock('@vehicle_search_list('+pageSize+', '+pageNum+')');
            res.status(200).json(result);
        } else {
            res.status(200).json({"success": false, "result": "参数验证失败，请查看控制台信息"});
        }
    });

    /**
     * 获取车辆轨迹
     */
    router.all('/vehicle/monitoring/detail', function(req, res) {
        helper.initValidator(req);
        req.check('VehicleID', 'VehicleID is required').notEmpty();
        req.check('StartTime', 'StartTime is required').notEmpty();
        req.check('EndTime', 'EndTime is required and').notEmpty();

        var errors = req.validationErrors();
        if (helper.checkValidationError(errors)) {
            // var vehicleId = req.params.VehicleID;
            // var startTime = req.params.StartTime;
            // var endTime = req.params.EndTime;
            var result = {};
            result.Ret = true;
            var items = new Array();
            // 生成假数据
            var lat = 34.797031;
            var lng = 113.698807;
            var now = new Date();
            for(var i = 0; i != 100; i++) {
                var item = {};
                item.Lat = lat + i * 0.0001;
                item.Long = lng + i * 0.0001;
                var newDate = new Date(now.getTime() + 1000 * i);
                item.Time = helper.formateDate(newDate, "yyyy-MM-dd hh:mm:ss");
                item.Speed = 60.00;

                items.push(item);
            }
            result.Items = items;
            res.status(200).json(result);
        } else {
            res.status(200).json({"success": false, "result": "参数验证失败，请查看控制台信息"});
        }
    });

    // mount the router on the app
    app.use('/mock', router);
};
